package top.lingkang.acgv.config.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import top.lingkang.acgv.config.auth.handler.CustomAccessDeniedHandler;
import top.lingkang.acgv.config.auth.handler.ExceptionTranslatorHandler;

@Configuration
@EnableResourceServer
public class ClientResourceConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private ExceptionTranslatorHandler exceptionTranslatorHandler;
    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .exceptionHandling()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //需要授权的路径
                .antMatchers("/api/**").hasAnyRole("USER")
                .anyRequest().permitAll(); //其他页面所有人能访问
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 配置资源 ID --对应sso的资源id
        resources.resourceId("backend-resources");
        OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        //自定义异常处理 401
        authenticationEntryPoint.setExceptionTranslator(exceptionTranslatorHandler);
        resources.authenticationEntryPoint(authenticationEntryPoint);

        //权限不足异常类重写 403
        resources.accessDeniedHandler(customAccessDeniedHandler);
    }
}
